package com.youlu.campus.service.activity.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityCostStatistics;
import com.youlu.campus.entity.ActivityCostStatisticsQueryVO;
import com.youlu.campus.service.activity.ActivityCostStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ActivityCostStatisticsServiceImpl implements ActivityCostStatisticsService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Page<ActivityCostStatistics> list(ActivityCostStatisticsQueryVO req) {
        log.info(":>>> 开始获取活动成本列表:{}", JSON.toJSON(req));
        if (Objects.isNull(req)) {
            log.error(":>>> 活动任务参数错误:活动统计ID不能为空");
            throw new BusinessException("活动统计ID不能为空");
        }
        Query query = new Query();
        if (StringUtils.isNotBlank(req.getActivityStatisticsId())) {
            query.addCriteria(Criteria.where("activityStatisticsId").is(req.getActivityStatisticsId()));
        }
        query.addCriteria(Criteria.where("deleted").ne(true));
        long count = mongoTemplate.count(query, ActivityCostStatistics.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ActivityCostStatistics> datas = mongoTemplate.find(query.with(pageRequest), ActivityCostStatistics.class);
        return PageableExecutionUtils.getPage(datas, pageRequest, () -> count);
    }

    @Override
    public void create(ActivityCostStatistics req) {
        req.setCreatedTime(new Date());
        req.setId(null);
        mongoTemplate.insert(req);

    }

    @Override
    public boolean update(ActivityCostStatistics req) {
        log.info(":>>> 开始修改活动成本:{}", JSON.toJSONString(req));
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        if (StringUtils.isNotBlank(req.getDepartment())) {
            update.set("department", req.getDepartment());
        }
        if (StringUtils.isNotBlank(req.getName())) {
            update.set("name", req.getName());
        }
        if (StringUtils.isNotBlank(req.getDesc())) {
            update.set("desc", req.getDesc());
        }
        if (Objects.nonNull(req.getCost())) {
            update.set("cost", req.getCost());
        }
        if (Objects.nonNull(req.getSpendingTime())) {
            update.set("spendingTime", req.getSpendingTime());
        }
        if (!CollectionUtils.isEmpty(req.getImageUrls())) {
            update.set("imageUrls", req.getImageUrls());
        }
        update.set("updatedTime", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ActivityCostStatistics.class);
        log.info(":>>> 修改活动成本:{},结果:{}", req.getId(), updateResult.getModifiedCount());
        return updateResult.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public boolean delete(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        DeleteResult deleteResult = mongoTemplate.remove(query, ActivityCostStatistics.class);
        return deleteResult.getDeletedCount() > 0 ? true : false;
    }

    @Override
    public ActivityCostStatistics findOne(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        ActivityCostStatistics a = mongoTemplate.findOne(query, ActivityCostStatistics.class);
        return a;
    }

    @Override
    public Double getTotalCost(String id) {
        log.info(":>>> 开始获取总成本:{}", id);
        Double cost = 0.00D;
        Query query = new Query().addCriteria(Criteria.where("activityStatisticsId").is(id));
        List<ActivityCostStatistics> datas = mongoTemplate.find(query, ActivityCostStatistics.class);
        for (ActivityCostStatistics a : datas) {
            if (Objects.nonNull(a.getCost())) {
                cost = cost + a.getCost();
            }
        }
        return cost;
    }

}
